<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        canvas{
            border: 1px solid #000;
            background-color: #ccc;
        }
    </style>
</head>
<body>
    <canvas width="500" height="400" id="myCanvas">
    </canvas>
    <script>
        // canvas的动画思想：清屏、更新、渲染，重新画
        var canvas = document.getElementById("myCanvas")
        // 获取上下文
        var ctx = canvas.getContext("2d")
        // 球类
        function Ball(x,y,r){
            this.x = x
            this.y = y
            this.r = r
            this.color = getRandom()
            // 设置行进方向
            this.dx = parseInt(Math.random() * 10) - 5
            // 设置行进方向
            this.dy = parseInt(Math.random() * 10) - 5

            ballArr.push(this)
        }

        Ball.prototype.update = function(){
            // 小球的运动
            this.x += this.dx
            this.y += this.dy
            this.r -= 0.4
            if(this.r < 0){
                this.remove()
            }
        }

        Ball.prototype.remove = function(){
            for(var i = 0; i < ballArr.length; i++){
                if(ballArr[i] == this){
                    ballArr.splice(i, 1)
                }
            }
        }
        
        // 渲染小球
        Ball.prototype.render = function(){
            ctx.beginPath()
            ctx.arc(this.x, this.y, this.r, 0, 2 * Math.PI, false)
            // console.log(this.x, this.y, this.color)
            ctx.fillStyle = this.color
            ctx.fill()
        }

        // canvas设置鼠标监听，鼠标移动的过程中创建小球
        canvas.addEventListener("mousemove", function(event){
            new Ball(event.offsetX, event.offsetY, 30)
        })
        
        // 维护小球的数组
        var ballArr = []
        // 定时器进行动画渲染和更新
        setInterval(function(){
            // 清除画布
            ctx.clearRect(0, 0, canvas.width, canvas.height)
            for(var i = 0; i < ballArr.length; i++){
                // 小球的更新和渲染
                ballArr[i].update()
                if(ballArr[i]){
                    ballArr[i].render()
                } 
            }
        },10)

        // 随机颜色
        function getRandom(){
            var allType = "0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f"
            var allTypeArr = allType.split(",")
            var color = "#"
            for (var i = 0; i < 6; i++){
                var random = parseInt(Math.random() * allTypeArr.length)
                color += allTypeArr[random]
            }
            return color
        }
    </script>
</body>
</html>